package com.mewpipe.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import com.mewpipe.dao.UserDao;
import com.mewpipe.entity.User;
import com.mewpipe.entity.UserSession;

public class JpaUserDao implements UserDao {

	private EntityManagerFactory emf;
	


	public JpaUserDao(EntityManagerFactory emf) {
	
			this.emf = emf;
		
			}
	@Override
	public void addUser(User _user) {
		
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(_user);
			em.getTransaction().commit();
			
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
		
		}
		
	}
	//Recuperation du User Complet depuis l'id  contenue dans la Variable "UserSession" mis en Session de l'application.
	@Override
	public User getUserInfo(long _id) {
		User return_user ;
		EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();
			return_user = em.find(User.class,_id);
			em.getTransaction().commit();
			
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
		
		}
		
			return return_user;
		
	}

	@Override
	public List<User> getAllUser() {
		EntityManager em = emf.createEntityManager();
		Query query= em.createQuery("FROM User u ");
		List<User> All_User = null;
		try {
			
			All_User = query.getResultList();
		} finally {
			em.close();
		}
		return All_User;
	}
	@Override
	public void deleteUserById(long _id) {
		EntityManager em=emf.createEntityManager();
		
		try {
			em.getTransaction().begin();
			
			User usertoremove = getUserInfo(_id);
			// On merge pour recuperer l'instance du User dans la MEME transaction que le REMOVE !!!
			usertoremove = em.merge(usertoremove);
			
			em.remove(usertoremove);
			em.getTransaction().commit();
			
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
		
		}
		
	}
	@Override
	public User getUserByName(String pseudo) {
		User return_user = null;
		EntityManager em = emf.createEntityManager();
		Query query = em.createQuery("FROM User u WHERE pseudo ='"+pseudo+"'");
		try {
			em.getTransaction().begin();
			List<User> users = query.getResultList();
			if(!users.isEmpty())
			return_user = users.get(0);
			else return_user = null;
			em.getTransaction().commit();
			
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
		
		}
		
		
			return return_user;
	}
}